# -*- coding: utf-8 -*-

from odoo import models, fields, api, exceptions
from datetime import datetime


class SpeechActivity(models.Model):
    _name = 'speech.activity'
    _description = '演讲活动'
    _order = 'create_date desc'
    _rec_name = 'title'

    title = fields.Char(string='会议标题', required=True, index=True)
    description = fields.Text(string='会议描述', required=True)
    rules = fields.Text(string='会议规则')
    
    # 可见性控制
    active = fields.Boolean(string='启用', default=True, help='取消勾选可隐藏此会议')
    
    # 模板类型
    template_type = fields.Selection([
        ('chinese', '中文模板'),
        ('english', '英文模板'),
    ], string='报名模板', default='chinese', required=True, help='选择会议使用的报名项目模板')
    
    # 联系人信息
    contact_name = fields.Char(string='联系人姓名')
    contact_wechat = fields.Char(string='联系人微信号')
    contact_phone = fields.Char(string='联系人手机号')
    
    # 地址信息
    address = fields.Char(string='会议地址')
    latitude = fields.Float(string='纬度', digits=(10, 6))
    longitude = fields.Float(string='经度', digits=(10, 6))
    
    start_time = fields.Datetime(string='会议开始时间', required=True)
    end_time = fields.Datetime(string='会议结束时间', required=True)
    
    registration_start_time = fields.Datetime(string='报名开始时间', required=True)
    registration_end_time = fields.Datetime(string='报名结束时间', required=True)
    
    voting_enabled = fields.Boolean(string='启用加油', default=False)
    voting_start_time = fields.Datetime(string='加油开始时间')
    voting_end_time = fields.Datetime(string='加油结束时间')
    max_votes_per_user = fields.Integer(string='每人限加油数', default=1)
    
    status = fields.Selection([
        ('unpublished', '未发布'),
        ('ongoing', '进行中'),
        ('finished', '已结束'),
        ('cancelled', '已取消')
    ], string='状态', default='unpublished', required=True)
    
    registration_ids = fields.One2many('speech.registration', 'activity_id', string='报名记录（旧）')
    item_ids = fields.One2many('activity.registration.item', 'activity_id', string='报名项目')
    registration_count = fields.Integer(string='报名数量', compute='_compute_counts')
    approved_registration_count = fields.Integer(string='已通过报名数', compute='_compute_counts')
    
    vote_ids = fields.One2many('speech.vote', 'activity_id', string='加油记录')
    vote_count = fields.Integer(string='加油数量', compute='_compute_counts')
    
    # 权限管理
    creator_id = fields.Many2one('wechat.user', string='创建人（微信用户）', index=True)
    manager_ids = fields.Many2many('wechat.user', 'speech_activity_manager_rel',
                                   'activity_id', 'user_id', string='活动管理员')
    
    @api.depends('item_ids', 'item_ids.registration_count', 'vote_ids')
    def _compute_counts(self):
        for record in self:
            # registration_count 统计所有报名项目的报名总数
            total_count = sum(item.registration_count for item in record.item_ids)
            record.registration_count = total_count
            record.approved_registration_count = total_count
            record.vote_count = len(record.vote_ids)

    @api.constrains('start_time', 'end_time')
    def _check_activity_dates(self):
        for record in self:
            if record.end_time <= record.start_time:
                raise exceptions.ValidationError('活动结束时间必须晚于开始时间！')

    @api.constrains('registration_start_time', 'registration_end_time')
    def _check_registration_dates(self):
        for record in self:
            if record.registration_end_time <= record.registration_start_time:
                raise exceptions.ValidationError('报名结束时间必须晚于开始时间！')

    @api.constrains('voting_start_time', 'voting_end_time', 'voting_enabled')
    def _check_voting_dates(self):
        for record in self:
            if record.voting_enabled:
                if not record.voting_start_time or not record.voting_end_time:
                    raise exceptions.ValidationError('启用加油时必须设置加油时间！')
                if record.voting_end_time <= record.voting_start_time:
                    raise exceptions.ValidationError('加油结束时间必须晚于开始时间！')

    def action_start(self):
        """开始活动"""
        self.write({'status': 'ongoing'})

    def action_finish(self):
        """结束活动"""
        self.write({'status': 'finished'})

    def action_cancel(self):
        """取消活动"""
        self.write({'status': 'cancelled'})

    def get_candidates(self):
        """获取候选人列表（已通过审核的报名）"""
        return self.registration_ids.filtered(lambda r: r.status == 'approved')

    def can_user_manage(self, user):
        """检查用户是否可以管理此活动"""
        if not user:
            return False
        
        # 全局管理员
        if user.role == 'admin':
            return True
        
        # 活动创建者
        if self.creator_id and self.creator_id.id == user.id:
            return True
        
        # 活动管理员
        if user in self.manager_ids:
            return True
        
        return False

    @api.model
    def cron_update_activity_status(self):
        """定时任务：更新活动状态（已发布的会议超过结束时间后自动改为已结束）"""
        now = fields.Datetime.now()
        
        # 结束已过期的会议
        ongoing_activities = self.search([
            ('status', '=', 'ongoing'),
            ('end_time', '<=', now)
        ])
        
        if ongoing_activities:
            ongoing_activities.write({'status': 'finished'})
            _logger.info(f'✅ 自动结束 {len(ongoing_activities)} 个会议')

